#include <Wire.h>					// include the standard Wire (I2C/TWI/2-wire) library

#include "Wally.h"

void getRTCtime(void)
{
	// Reset the register pointer
	Wire.beginTransmission(slaveRTC);
	Wire.write((byte)0x00);
	Wire.endTransmission();

	Wire.requestFrom(slaveRTC, 7);
	int second = bcd2dec(Wire.read());
	int minute = bcd2dec(Wire.read());
	int hour = bcd2dec(Wire.read() & 0b111111);	//24 hour time
	int weekDay = bcd2dec(Wire.read()); 		//0-6 -> sunday - Saturday
	int monthDay = bcd2dec(Wire.read());
	int month = bcd2dec(Wire.read());
	int year = bcd2dec(Wire.read());

	//print the date :  d/m/YY 23:59:59
	Serial.print(monthDay);
	Serial.print("/");
	Serial.print(month);
	Serial.print("/");
	Serial.print(year);
	Serial.print(" ");
	Serial.print(hour);
	Serial.print(":");
	Serial.print(minute);
	Serial.print(":");
	Serial.println(second);

	delay(500);
}

void setRTCtime(void)
{
  	byte second =		45;	//0-59
  	byte minute =		40;	//0-59
  	byte hour =			0;	//0-23
  	byte weekDay =		2;	//1-7
  	byte monthDay =		1;	//1-31
  	byte month =		3;	//1-12
  	byte year  =		11;	//0-99

	Wire.beginTransmission(slaveRTC);
	Wire.write((byte)0x00); //stop Oscillator

	Wire.write(dec2bcd(second));
	Wire.write(dec2bcd(minute));
	Wire.write(dec2bcd(hour));
	Wire.write(dec2bcd(weekDay));
	Wire.write(dec2bcd(monthDay));
	Wire.write(dec2bcd(month));
	Wire.write(dec2bcd(year));
	Wire.write((byte)0x00); //start Oscillator

  Wire.endTransmission();

}

// convert bin to BCD
byte dec2bcd(byte val){
	return ((val/10*16)+(val%10));
}

// convert BCD to binary
byte bcd2dec(byte val){
	return ((val/16*10)+(val%16));
}